# -*- coding: utf-8 -*-
from flask import Blueprint, g
from sqlalchemy import or_
from common.response import success, error
from common.error_code import ErrorCode
from filter.auth import auth_required
from filter.decorators import validate_request, require_role
from model.request import ListStudentsRequest, UpdateStudentRequest
from dao.db import db
from dao.user_dao import User, Student, Class, Teacher
from dao.class_dao import ClassSubjectTeacher

# 创建学生管理蓝图
studentmgr_bp = Blueprint('studentmgr', __name__, url_prefix='/api/studentmgr')

@studentmgr_bp.route('/list-students', methods=['POST'])
@auth_required
@require_role(['admin', 'teacher'])
@validate_request(ListStudentsRequest)
def list_students():
    """查询学生列表接口"""
    params = g.request_data
    class_id = params.class_id
    name_keyword = params.name.strip() if params.name else None
    has_group = params.has_group

    # 1. 权限与参数校验
    if g.role == 'teacher':
        if not class_id:
            return error(ErrorCode.INVALID_PARAM, "教师调用时class_id为必选参数")

        # 检查班级是否存在
        cls = Class.query.get(class_id)
        if not cls:
            return error(ErrorCode.NOT_FOUND, f"班级ID={class_id}不存在")

        # 检查该老师是否是这个班级的班主任或任课老师
        teacher = Teacher.query.filter_by(user_id=g.user_id).first()
        is_head_teacher = (cls.head_teacher_id == teacher.id)
        is_subject_teacher = ClassSubjectTeacher.query.filter_by(
            class_id=class_id,
            teacher_id=teacher.id
        ).first()

        if not is_head_teacher and not is_subject_teacher:
            return error(ErrorCode.FORBIDDEN, "你不是该班级的班主任或任课老师，无权查询")

    # 2. 构建查询
    query = db.session.query(
        User.id.label('user_id'),
        Student.id,
        Student.student_id,
        User.name.label('student_name'),
        Class.name.label('class_name'),
        Class.grade
    ).join(Student, User.id == Student.user_id
    ).join(Class, Student.class_id == Class.id)

    # 3. 筛选条件
    if class_id:
        query = query.filter(Student.class_id == class_id)

    if name_keyword:
        query = query.filter(User.name.like(f'%{name_keyword}%'))
    
    if has_group != None:
        query = query.filter(Student.group_id.is_(None)) if has_group == 0 else query.filter(Student.group_id.isnot_(None))

    # 4. 排序
    query = query.order_by(
        Class.grade.asc(),
        Class.name.asc(),
        Student.student_id.asc()
    )

    # 5. 执行查询
    students = query.all()

    # 6. 格式化返回
    result = [
        {
            "user_id": s.user_id,
            "student_id": s.id,
            "student_number": s.student_id,
            "name": s.student_name,
            "class_name": s.class_name,
            "grade": s.grade
        }
        for s in students
    ]

    return success(result)

@studentmgr_bp.route('/update-student', methods=['POST'])
@auth_required
@require_role(['admin', 'teacher'])
@validate_request(UpdateStudentRequest)
def update_student():
    """修改学生信息接口"""
    data = g.request_data

    # 1. 验证管理员/教师口令
    current_teacher = Teacher.query.filter_by(user_id=g.user_id).first()
    if not current_teacher:
        return error(ErrorCode.FORBIDDEN, "当前用户不是教师，无法验证口令")

    if current_teacher.password_hash != data.admin_password:
        return error(ErrorCode.INVALID_PARAM, "管理员/教师口令错误")

    # 2. 查找学生
    student_user = User.query.filter_by(id=data.user_id, role='student').first()
    if not student_user:
        return error(ErrorCode.NOT_FOUND, "学生不存在")

    student_info = Student.query.filter_by(user_id=data.user_id).first()
    if not student_info:
        return error(ErrorCode.NOT_FOUND, "学生信息不存在")

    # 3. 如果是teacher权限，检查是否有权限管理该学生
    if g.role == 'teacher':
        # 获取学生当前所在班级
        student_class_id = student_info.class_id

        # 检查班级是否存在
        cls = Class.query.get(student_class_id)
        if not cls:
            return error(ErrorCode.NOT_FOUND, "学生所在班级不存在")
        
        if cls.grade >= 10:
            return error(ErrorCode.NOT_FOUND, "已毕业的学生资料无法修改")

        # 检查该老师是否是这个班级的班主任或任课老师
        is_head_teacher = (cls.head_teacher_id == current_teacher.id)
        is_subject_teacher = ClassSubjectTeacher.query.filter_by(
            class_id=student_class_id,
            teacher_id=current_teacher.id
        ).first()

        if not is_head_teacher and not is_subject_teacher:
            return error(ErrorCode.FORBIDDEN, "你不是该学生所在班级的班主任或任课老师，无权修改")

    # 4. 检查新班级是否存在（如果提供）
    if data.class_id is not None:
        new_class = Class.query.get(data.class_id)
        if not new_class:
            return error(ErrorCode.NOT_FOUND, f"班级ID={data.class_id}不存在")

        # 检查新班级是否已毕业
        if new_class.grade >= 10:
            return error(ErrorCode.FORBIDDEN, "不能将学生移入已毕业班级")

    # 5. 检查新学号是否重复（如果提供）
    if data.student_id is not None:
        # 确定学生最终所在班级
        final_class_id = data.class_id if data.class_id is not None else student_info.class_id

        # 检查同班内学号是否重复
        if Student.query.filter_by(
            class_id=final_class_id,
            student_id=data.student_id
        ).first():
            return error(ErrorCode.INVALID_PARAM, "该学号在本班已存在")

    # 6. 更新字段（有值才更新）
    if data.name is not None:
        student_user.name = data.name

    if data.username is not None:
        # 检查用户名是否已存在
        if User.query.filter_by(username=data.username).first():
            return error(ErrorCode.INVALID_PARAM, "用户名已存在")
        student_user.username = data.username

    if data.password is not None:
        student_user.password = data.password

    if data.class_id is not None:
        student_info.class_id = data.class_id

    if data.student_id is not None:
        student_info.student_id = data.student_id
    
    if data.school_position is not None:
        student_info.school_position = data.school_position

    if data.class_position is not None:
        student_info.class_position = data.class_position

    db.session.commit()

    # 7. 返回更新后的学生信息
    return success({
        "user_id": student_user.id,
        "username": student_user.username,
        "name": student_user.name,
        "student_id": student_info.student_id,
        "class_id": student_info.class_id
    })